package test

import (
	"bytes"
	"encoding/json"
	"net/http/httptest"
	"net/url"
	"strings"

	"github.com/gin-gonic/gin"
)

// 用于单元测试，类似http.PostForm
// 例：
//		r := gin.New()
//
//		rr := RequestForm(r, "POST", "/users", url.Values{
//			"username": {"konglw"},
//		})
//		assert.Equal(t, 200, rr.Code)
func RequestForm(r *gin.Engine, method, url string, data url.Values) *httptest.ResponseRecorder {
	rr := httptest.NewRecorder()

	req := httptest.NewRequest(method, url, strings.NewReader(data.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	r.ServeHTTP(rr, req)

	return rr
}

// 用于单元测试
// 例：
//		r := gin.New()
//
//		rr = RequestJson(r, "POST", "/users", gin.H{
//			"username": "konglw",
//		})
//		assert.Equal(t, 200, rr.Code)
func RequestJson(r *gin.Engine, method, url string, data gin.H) *httptest.ResponseRecorder {
	rr := httptest.NewRecorder()
	jsonBytes, _ := json.Marshal(data)

	req := httptest.NewRequest(method, url, bytes.NewReader(jsonBytes))
	req.Header.Set("Content-Type", "application/json")

	r.ServeHTTP(rr, req)

	return rr
}

// 用于单元测试
// 例：
//		r := gin.New()
//
//		rr = Request(r, "GET", "/users")
//		assert.Equal(t, 200, rr.Code)
func Request(r *gin.Engine, method, url string) *httptest.ResponseRecorder {
	rr := httptest.NewRecorder()
	req := httptest.NewRequest(method, url, nil)

	r.ServeHTTP(rr, req)
	return rr
}
